﻿@{
    Layout = "~/Areas/Admin/Views/Shared/BlogGl.cshtml";
    ViewBag.Title = "博客文章管理";
}
<style>
    .layui-form-select {
        position: relative;
        width: 95%;
    }
</style>
<div style="padding: 15px 20px;">
    <div class="layui-elem-quote">
        <p>@ViewBag.Title</p>
    </div>
    <div>
        <div>
            <input type="text" id="soutitle" placeholder="标题" autocomplete="off" class="layui-input" style="width:15%;float:left;">
            <button class="layui-btn layui-btn-lg" onclick="sousuoblog()" style="margin-left:20px;">
                <i class="layui-icon">&#xe615;</i>搜索
            </button>
            <button class="layui-btn layui-btn-lg" onclick="add('添加文章')">
                <i class="layui-icon">&#xe608;</i> 添加
            </button>
        </div>
    </div>
    <script type="text/html" id="indexTpl">
        {{d.LAY_TABLE_INDEX+1}}
    </script>
    <table id="demo" lay-filter="tools"></table>
    <div id="laypage"></div>
    <script type="text/html" id="barDemo">
        @*<a class="layui-btn layui-btn-xs" lay-event="detail">查看</a>*@
        <a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
        <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    </script>
</div>
<form class="layui-form" style="padding-top:20px;display:none;" method="post" action="/Blog/addblogartcle" name="formarticle" id="formarticle">
    <div class="layui-form-item">
        <label class="layui-form-label">标题</label>
        <div class="layui-input-block">
            <input type="text" name="BlogArticleTitle" id="BlogArticleTitle" style="width:30%;" lay-verify="required" placeholder="请输入标题" autocomplete="off" class="layui-input" />
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">博客标签</label>
        <div class="layui-input-block">
            <input type="text" id="BlogLableName" style="width:30%;" required lay-verify="required" placeholder="请选择标签" readonly class="layui-input" onclick="bolglable(this)" />
            <input type="text" name="BlogLableBh" id="BlogLableBh" style="width:30%;display:none;" required class="layui-input" />
            <input type="text" name="Id" id="Id" style="width:30%;display:none;" required class="layui-input" />
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">排序值</label>
        <div class="layui-input-block">
            <input type="text" name="BlogArticleSortValue" id="BlogArticleSortValue" style="width:10%;float:left" required lay-verify="required|number" value="0" placeholder="排序值" autocomplete="off" class="layui-input">
            <label class="layui-form-label" style="text-align:center">是否置顶</label>
            <input type="checkbox" lay-filter="sw" lay-skin="switch" lay-text="是|否">
        </div>

    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">浏览量</label>
        <div class="layui-input-block">
            <input type="text" id="BlogArticleBrowsingNum" style="width:30%;" value="0" disabled class="layui-input layui-disabled">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">点赞量</label>
        <div class="layui-input-block">
            <input type="text" id="BlogArticleLikeNum" style="width:30%;" value="0" disabled class="layui-input layui-disabled">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">评论量</label>
        <div class="layui-input-block">
            <input type="text" id="BlogArticleCommentNum" style="width:30%;" value="0" disabled class="layui-input layui-disabled">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label"></label>
        <div class="layui-input-block">
            <a href="https://www.zybuluo.com/mdeditor" target="_blank" class="layui-btn layui-btn-normal">Cmd Markdown(在线编辑器)</a>(使用方法)在Cmd Markdown写好内容之后拷贝到下方编辑器即可
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">内容</label>
        <div class="layui-input-block">
            <textarea id="edits" name="edits" style="display: none;width:90%;"></textarea>
        </div>
    </div>
    <div class="layui-form-item layui-form-text">
        <label class="layui-form-label">备注</label>
        <div class="layui-input-block">
            <input type="text" name="BlogArticleNote" id="BlogArticleNote" placeholder="备注" style="width:30%;" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <div class="layui-input-block">
            <button class="layui-btn" lay-submit lay-filter="formDemo">立即提交</button>
            <button type="reset" class="layui-btn layui-btn-primary">重置</button>
        </div>
    </div>
</form>
<div id="bolglable">
    <form class="layui-form" action="">
        <div class="layui-form-item">
            <label class="layui-form-label" style="display:none">博客标签</label>
            <div class="layui-input-block">
                @*<input type="checkbox" name="like[write]" title="写作">
                    <input type="checkbox" name="like[read]" title="阅读" checked>
                    <input type="checkbox" name="like[dai]" title="发呆">*@
            </div>
        </div>
        <button class="layui-btn" style="position:absolute;bottom:10px;right:10px;display:none" lay-submit lay-filter="*">确定</button>
    </form>

</div>
<script>
    $(function () {
        getpagecount({});

    })
    function sousuoblog() {
        getpagecount({ blogtitle: $("#soutitle").val() });
    }
    function getpagecount(data) {
        layui.use(['table', 'laypage'], function () {
            var table = layui.table,
                laypage = layui.laypage;;
            //第一个实例
            var tableindex = table.render({
                elem: '#demo'
                 , height: 700
                 , url: '/Blog/articlepage' //数据接口
                 , where: data
                 , page: {
                     groups: 10,
                     limit: 20,
                     limits: [20, 50],
                     layout: ['first', 'prev', 'page', 'next', 'last', 'limit', 'count', 'skip']
                 }
                 , even: true
                 , cols: [[ //表头
                     { templet: '#indexTpl', title: '序号', width: 60, fixed: 'center' }
                   , { field: 'Id', title: 'Id', width: 120, sort: true, fixed: 'left' }
                   , { field: 'BlogArticleTitle', title: '博客文章标题', width: 150 }
                   , { field: 'BlogArticleSortValue', title: '排序值', width: 110, sort: true }
                   , { field: 'BlogArticleBrowsingNum', title: '浏览量', width: 110 }
                   , { field: 'BlogArticleLikeNum', title: '点赞量', width: 110 }
                   , { field: 'BlogArticleCommentNum', title: '评论量', width: 110, sort: true }
                   , { field: 'BlogArticleCreateTime', title: '创建时间', width: 180, sort: true }
                   , { field: 'BlogArticleBody', title: '博客内容', width: 120, }
                   , { field: 'BlogArticleNote', title: '备注', width: 200 }
                   , { fixed: 'right', title: '操作', width: 200, align: 'center', toolbar: '#barDemo' } //这里的toolbar值是模板元素的选择器
                 ]]
                , done: function (res, curr, count) {
                    ////如果是异步请求数据方式，res即为你接口返回的信息。
                    ////如果是直接赋值的方式，res即为：{data: [], count: 99} data为当前页数据、count为数据总长度
                    //console.log(res);
                    ////得到当前页码
                    //console.log(curr);
                    ////得到数据总量
                    //console.log(count);
                    //var tables = $("#demo").next().find(".layui-table-box");
                    //tables.find("[data-field='BlogArticleBody']").css("display", "none");
                }
            });
            table.on('tool(tools)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
                var data = obj.data; //获得当前行数据
                var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
                var tr = obj.tr; //获得当前行 tr 的DOM对象
                if (layEvent === 'del') { //删除
                    layer.confirm('真的删除么', function (index) {
                        obj.del(); //删除对应行（tr）的DOM结构，并更新缓存
                        layer.close(index);
                        //向服务端发送删除指令
                        $.post("/Blog/blogdel", {
                            id: data.Id,
                        }, function (data, stauts) {
                            if (JSON.parse(data).StateCode == 200)
                                getpagecount({});
                            else
                                console.log(data);
                        });
                    });
                } else if (layEvent === 'edit') { //编辑
                    //do something
                    add('修改文章', data);
                }
            });
        });
    }
    function HTMLEncode(html) {
        var temp = document.createElement("div");
        (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
        var output = temp.innerHTML;
        temp = null;
        return output;
    }
    function HTMLDecode(text) {
        var temp = document.createElement("div");
        temp.innerHTML = text;
        var output = temp.innerText || temp.textContent;
        temp = null;
        return output;
    }
    function add(_title, data) {
        var state = 0;//0代表添加
        if (data != undefined) {
            console.log(data);
            document.getElementById('BlogArticleTitle').value = data.BlogArticleTitle;
            document.getElementById('BlogArticleSortValue').value = data.BlogArticleSortValue;
            document.getElementById('BlogArticleBrowsingNum').value = data.BlogArticleBrowsingNum;
            document.getElementById('BlogArticleLikeNum').value = data.BlogArticleLikeNum;
            document.getElementById('BlogArticleCommentNum').value = data.BlogArticleCommentNum;
            document.getElementById('BlogArticleNote').value = data.BlogArticleNote;
            document.getElementById('edits').value = data.BlogArticleBody;
            document.getElementById('Id').value = data.Id;
            state = 1;//0代表修改
            //获取文章标签
            $.get("/Blog/getBlogRelated?BlogRelatedArticleId=" + data.Id + "", function (data, state) {
                var jsonData = JSON.parse(data);
                if (jsonData.StateCode = 200) {
                    var bolglablebh = "", bolglablename = "";
                    for (var v in jsonData.JsonData) {
                        bolglablebh += jsonData.JsonData[v].BlogLableBh + ",";
                        bolglablename += jsonData.JsonData[v].BlogLableName + ",";
                    }
                    $('#BlogLableBh').val(bolglablebh.substring(0, bolglablebh.length - 1));
                    $('#BlogLableName').val(bolglablename.substring(0, bolglablename.length - 1));
                }
            })
        } else
            $('#formarticle')[0].reset();
        layui.use('form', function () {
            var form = layui.form;
            var openindex = layer.open({
                type: 1,
                title: _title,
                shadeClose: true,
                area: ['90%', '90%'],
                content: $('#formarticle'), //这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                success: function (layero, index) {
                    layui.use('layedit', function () {
                        var layedit = layui.layedit;
                        layedit.set({
                            uploadImage: {
                                url: '/Blog/uploadimg' //上传图片接口url
                            }
                        });
                        var editIndex = layedit.build('edits', {
                            tool: [
                                  'strong' //加粗
                                  , 'italic' //斜体
                                  , 'underline' //下划线
                                  , 'del' //删除线
                                  , '|' //分割线
                                  , 'left' //左对齐
                                  , 'center' //居中对齐
                                  , 'right' //右对齐
                                  , 'link' //超链接
                                  , 'unlink' //清除链接
                                  , 'face' //表情
                                  , 'image' //插入图片
                                  , 'help' //帮助
                            ]
                        }); //建立编辑器
                        sessionStorage.BlogArticleSortValue = $('#BlogArticleSortValue').val();
                        form.on('switch(sw)', function (data) {
                            if (data.elem.checked) {
                                $.get("/Blog/bolgsortmax", function (data, stauts) {
                                    $('#BlogArticleSortValue').val(data * 1 + 1);
                                });
                            } else {
                                // console.log(sort)
                                $('#BlogArticleSortValue').val(sessionStorage.BlogArticleSortValue);
                            }
                        });
                        form.on('submit(formDemo)', function (data) {
                            // console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
                            //console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
                            if (layedit.getContent(editIndex) == '') {
                                layer.msg('请填写文章内容');
                                return false;
                            }
                            data.field.state = state;
                            data.field.edits = layedit.getContent(editIndex);
                            console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
                            formIsDirty(document.forms["formarticle"], data.field);
                            var loadindex = layer.load(2, { time: 20 * 1000 }); //又换了种风格，并且设定最长等待10秒 
                            $.post("/Blog/addblogartcle", data.field, function (data, status) {
                                layer.close(loadindex);
                                layer.close(openindex);
                                getpagecount({});
                                if (JSON.parse(data).StateCode == 200) {
                                    layer.msg(JSON.parse(data).Messages);
                                }
                                else {
                                    layer.open({
                                        title: '提示'
                                      , content: JSON.parse(data).Messages
                                    });
                                }
                            })
                            return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                        });
                    });
                },
                end: function () {
                    $('#formarticle').hide();
                }
            });

        });
    }
    function bolglable(_this) {
        var lablenames = $(_this).val().split(',');
        layui.use('form', function () {
            var form = layui.form;
            $.get("/Blog/getbolglable", function (data, status) {
                var json = JSON.parse(data);
                if (json.length > 0) {
                    $('#bolglable').find('.layui-input-block').empty();
                    for (v in json) {
                        if (lablenames.indexOf(json[v].BlogLableName) >= 0) {
                            $('#bolglable').find('.layui-input-block').append("<input type=\"checkbox\" checked name=\"" + json[v].BlogLableBh + "_" + json[v].BlogLableName + "\" title=\"" + json[v].BlogLableName + "\">");
                        }
                        else {
                            $('#bolglable').find('.layui-input-block').append("<input type=\"checkbox\" name=\"" + json[v].BlogLableBh + "_" + json[v].BlogLableName + "\" title=\"" + json[v].BlogLableName + "\">");
                        }

                    }
                    var index = layer.open({
                        type: 1,
                        title: '博客标签选择',
                        shadeClose: true,
                        area: ['50%', '50%'],
                        content: $('#bolglable'),
                        success: function (layero, index) {
                            $('#bolglable').show();
                            $('#bolglable').find('button').show();
                            $('#bolglable').find('label').show();
                        },
                        end: function () {
                            $('#bolglable').hide();
                            $('#bolglable').find('button').hide();
                            $('#bolglable').find('label').hide();
                        }//这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                    });
                    form.render();//重新渲染表单
                    form.on('submit(*)', function (data) {
                        //console.log(data.elem) //被执行事件的元素DOM对象，一般为button对象
                        //console.log(data.form) //被执行提交的form对象，一般在存在form标签时才会返回
                        //console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}
                        var bolglablebh = "";
                        var bolglablename = "";
                        for (v in data.field) {
                            bolglablebh += v.split('_')[0] + ',';
                            bolglablename += v.split('_')[1] + ',';
                        }
                        $('#BlogLableBh').val(bolglablebh.substring(0, bolglablebh.length - 1));
                        $('#BlogLableName').val(bolglablename.substring(0, bolglablename.length - 1));
                        layer.close(index);
                        return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
                    });
                }
            });
        });
    }
    /*判断表单是否被修改*/
    function formIsDirty(form,data) {
        var formdata = [];
        for (var i = 0; i < form.elements.length; i++) {
            var element = form.elements[i];
            if (element.id != '')
                formdata.push({ id: element.id, value: element.value });
        }
        console.log(formdata);

    }
</script>
